package com.heo.music.player.service.impl;

import com.heo.music.player.auth.UserInfoContextHolder;
import com.heo.music.player.converter.MusicCommentConverter;
import com.heo.music.player.dao.MusicCommentDao;
import com.heo.music.player.dao.MusicInfoDao;
import com.heo.music.player.dto.input.MusicCommentInput;
import com.heo.music.player.dto.output.MusicCommentOutput;
import com.heo.music.player.dto.output.PageOutput;
import com.heo.music.player.dto.query.PageQuery;
import com.heo.music.player.entity.MusicComment;
import com.heo.music.player.entity.MusicInfo;
import com.heo.music.player.entity.UserInfo;
import com.heo.music.player.service.MusicCommentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;


@Service
@Slf4j
@RequiredArgsConstructor
public class MusicCommentServiceImpl implements MusicCommentService {

    public final MusicCommentDao musicCommentDao;

    private final MusicInfoDao musicInfoDao;

    private final MusicCommentConverter musicCommentConverter;

    @Override
    public PageOutput<MusicCommentOutput> findAllMusicComment(Integer musicId, PageQuery pageQuery) {
        Pageable pageable = pageQuery.convertPageable();
        MusicInfo musicInfo = getMusicInfoById(musicId);
        Page<MusicComment> musicInfoPage = musicCommentDao.findAllByMusicInfo(musicInfo, pageable);
        return musicCommentConverter.convert(musicInfoPage);
    }


    @Override
    public MusicCommentOutput createMusicComment(Integer musicId, MusicCommentInput input) {
        MusicInfo musicInfo = getMusicInfoById(musicId);
        UserInfo userInfo = UserInfoContextHolder.getUserInfo();
        MusicComment musicComment = new MusicComment();
        musicComment.setMusicInfo(musicInfo);
        musicComment.setUserInfo(userInfo);
        musicComment.setContent(input.getContent());
        musicCommentDao.save(musicComment);
        return musicCommentConverter.convert(musicComment);
    }

    private MusicInfo getMusicInfoById(Integer musicId) {
        return musicInfoDao.findById(musicId).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "音乐不存在"));
    }
}
